<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <el-tab-pane label="角色管理">
            <el-row style="height:60px">
              <el-button size="mini" icon="el-icon-plus" type="primary" @click="addRole">  新增角色</el-button>
            </el-row>
            <el-table border="" :data="roleList">
              <el-table-column label="序号" width="120">
                <template #default="{$index}">
                  {{ (page.page - 1) * page.pagesize + ($index + 1) }}
                </template>
              </el-table-column>
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="assignPermissions(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next"
                :total="page.total"
                :page-size="page.pagesize"
                @current-change="currentChange"
              />
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title="dialogTitle" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog title="权限分配" :visible="showassignPermissions" @close="premisson">
        <el-tree
          ref="premiss"
          :data="permisslist"
          :props="{label:'name'}"
          default-expand-all
          :show-checkbox="true"
          :check-strictly="true"
          node-key="id"
        />
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button @click="premissok">确定</el-button>
            <el-button @click="premisson">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getCompanyInfo, getRoleList, delRole, getRoleDetail, editRole, addRole, assignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { listToTreeData } from '@/utils'
export default {
  data() {
    const checkNameRepeat = async(rule, val, callback) => {
      const { rows } = await getRoleList({ page: 1, pagesize: this.page.total })
      if (rows.some(item => item.name === val && item.id !== this.roleForm.id)) {
        callback(new Error('名字不能重复'))
      } else {
        callback()
      }
    }
    return {
      roseod: '',
      permisslist: [],
      select: [],
      showassignPermissions: false,
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          { trigger: 'blur', validator: checkNameRepeat }
        ],
        description: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ]
      },
      formData: {

      },
      roleList: [],
      page: {
        page: 1,
        pagesize: 2, total: 0
      }
    }
  },
  computed: {
    ...mapGetters(['companyId']),
    dialogTitle() {
      return this.roleForm.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getCompanyInfo()
    this.getRoleList()
  },
  methods: {
    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.companyId)
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.page)
      this.roleList = rows
      this.page.total = total
    },
    currentChange(newPage) {
      this.page.page = newPage
      this.getRoleList()
    },
    async delRole(id) {
      try {
        // 二次校验
        await this.$confirm('是否确认删除?')
        // 发请求
        await delRole(id)
        // 更新页面
        if (this.roleList.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        this.getRoleList()
        // 提醒用户
        this.$message.success('删除完毕')
      } catch (error) {
        console.log(error)
      }
    },
    addRole() {
      this.showDialog = true
    },
    async editRole(id) {
      // 回显数据
      this.roleForm = await getRoleDetail(id)
      // 弹窗
      this.showDialog = true
    },
    async btnOK() {
      // 校验表单
      if (this.roleForm.id) {
        // 编辑
        await editRole(this.roleForm)
      } else {
        // 新增
        await addRole(this.roleForm)
      }
      // 提示用户
      this.$message.success('操作成功')
      // 更新页面
      this.getRoleList()
      // 关闭弹窗
      this.showDialog = false
    },
    btnCancel() {
      // 1. 清理表单
      this.roleForm = {
        name: '',
        description: ''
      }
      // 2. 清理校验
      this.$refs.roleForm.resetFields()
      // 3. 关闭弹窗
      this.showDialog = false
    },
    async assignPermissions(id) {
      const res = await getPermissionList(id)
      this.permisslist = listToTreeData(res, '0')
      const { permIds } = await getRoleDetail(id)
      this.select = permIds
      this.roseod = id
      this.showassignPermissions = true
      this.$nextTick(() => {
        this.$refs.premiss.setCheckedKeys(this.select)
      })
    },
    // 分配权限
    async  premissok() {
      await assignPerm({
        id: this.roseod,
        permIds: this.$refs.premiss.getCheckedKeys()
      })
      this.$message.success('操作成功')
      this.showassignPermissions = false
    },
    premisson() {
      this.showassignPermissions = false
    }
  }
}

</script>

<style>

</style>
